<?php
/**
 * Created by PhpStorm.
 * User: 墨鱼行
 * Signature: 好好学习，天天向上
 * Date: 19-2-25
 * Time: 下午10:34
 */

namespace app\api\service;


use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class Token
{
    /**
     * 生成Token
     * @param $uid
     * @return string
     */
    public static function generateToken($uid)
    {
        $randChar  = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $salt      = config('wx.token_salt');
        return md5($uid . $randChar . $timestamp . $salt);
    }

    /**
     * 获取token变量信息
     * @param $key
     * @return mixed
     * @throws Exception
     * @throws \app\lib\exception\ThrowError
     */
    public static function getTokenVal($key)
    {
        $token = Request::instance()
            ->header('token');

        if (empty($token))
        {
            T(600001);
        }

        $cacheValue = Cache::get($token);

        if (empty($cacheValue))
        {
            T(600002, [], 401);
        }
        else
        {
            if (!is_array($cacheValue))
            {
                $cacheValue = json_decode($cacheValue, true);
            }

            if (array_key_exists($key, $cacheValue))
            {
                return $cacheValue[$key];
            }
            else
            {
                throw new Exception('尝试或者的token变量不存在');
            }
        }
    }

    /**
     * 获取当前用户uid
     * @return mixed
     * @throws Exception
     * @throws \app\lib\exception\ThrowError
     */
    public static function getCurrentUid()
    {
        $uid = self::getTokenVal('uid');
        return $uid;
    }

    /**
     * 验证Token
     * @param $token
     * @return bool
     */
    public static function verifyToken($token)
    {
        $cacheValue = Cache::get($token);
        if (empty($cacheValue))
        {
            return false;
        }
        return true;
    }
}